package com.iwhalecloud.bss.kite.cucc.web.controller.opp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceBus;
import com.ztesoft.bss.common.util.ContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@RestController
@RequestMapping("/oppInfo")
@Api(tags = {"/oppInfo - 定制包商机查询展示页"})
public class OppinfoController {

    @Autowired
    private InfServiceBus infServiceBus;
    @ApiOperation(value = "查询商机列表", notes = "查询商机列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "creator", value = "创建人登录名或手机号"),
        @ApiImplicitParam(name = "oppoNum", value = "商机编号"),
        @ApiImplicitParam(name = "oppoName", value = "商机名称"),
        @ApiImplicitParam(name = "custName", value = "客户名称"),
        @ApiImplicitParam(name = "page", value = "页码"),
        @ApiImplicitParam(name = "size", value = "每页条数"),
        @ApiImplicitParam(name = "processStatus", value = "流程状态")//流程状态，0-未完成，1-已完成，2-废弃
    })
    @GetMapping("/list")
    public DataResult<Map> list(String  creator, String  oppoNum, String  oppoName, String  custName, String  page, String  size, String  processStatus) {
       /* CuccLoginInfoDTO cuccLoginInfo = new CuccLoginInfoDTO();*/
        Map map=new HashMap();
        map.put("creator",KiteStringUtils.isNotEmpty(creator)?creator: ContextUtil.getLoginInfo().getStaffInfo().getStaffCode());
        map.put("oppoNum",oppoNum);
        map.put("oppoName",oppoName);
        map.put("custName",custName);
        map.put("page",page);
        map.put("size",size);
        //4 已完成和已转定
        map.put("processStatus","4");
        Map<String, Object> list = infServiceBus.queryOppInfoList(map);
        timeMillisFormate(list);
        return ErrorConsts.SUCCESS.getResult(list);
    }
    @ApiOperation(value = "查询商机详情", notes = "查询商机详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "oppoNum", value = "商机编号")
    })
    @GetMapping("/detail")
    public DataResult<Map> detail(String  oppoNum) {
        Map map=new HashMap();
        map.put("oppoNum",oppoNum);
        Map<String, Object> list = infServiceBus.queryOppInfodetail(map);
        dealGroupOppo(list);
        return ErrorConsts.SUCCESS.getResult(list);
    }
    @ApiOperation(value = "合作伙伴新增查询接口", notes = "合作伙伴新增查询接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ENT_NAME", value = "合作伙伴名称")
    })
    @GetMapping("/newPartnerQuery")
    public DataResult<Map> newPartnerQuery(String  ENT_NAME) {
        Map map=new HashMap();
        map.put("ENT_NAME",ENT_NAME);
        Map<String, Object> list = infServiceBus.queryNewPartnerQuery(map);
        return ErrorConsts.SUCCESS.getResult(list);
    }
    @ApiOperation(value = "查询合作伙伴复用接口", notes = "查询合作伙伴复用接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "BUSINESS_NO", value = "商机编号")
    })
    @GetMapping("/partnerReuseQuery")
    public DataResult<Map> partnerReuseQuery(String  BUSINESS_NO) {
        Map map=new HashMap();
        map.put("BUSINESS_NO",BUSINESS_NO);
        Map<String, Object> list = infServiceBus.partnerReuseQuery(map);
        return ErrorConsts.SUCCESS.getResult(list);
    }
    @ApiOperation(value = "下载附件", notes = "下载附件")
    @ApiImplicitParams({@ApiImplicitParam(name = "attachLocation", value = "附件在FTP上的名称")
    })
    @GetMapping("/file")
    public DataResult<String> getViewUrl(String  attachLocation) {
        Map map=new HashMap();
        map.put("attachLocation",attachLocation);
        return ErrorConsts.SUCCESS.getResult(infServiceBus.getDownLoadFile(map));
    }
    private void timeMillisFormate(Map<String, Object> oppoMap){
        List oppoStr = (List)KiteMapUtils.getObject(oppoMap,"oppoResList");
        if(KiteListUtils.isNotEmpty(oppoStr)){
            if(KiteListUtils.isNotEmpty(oppoStr)){
                oppoStr.forEach(oppoJson->{
                    Map jsonObject = (Map) oppoJson;
                    Map oppoRes = KiteMapUtils.getMap(jsonObject, "oppoRes");
                    String signTime = KiteMapUtils.getString(oppoRes,"signTime");
                    if(KiteStringUtils.isNum(signTime)){
                        SimpleDateFormat sdf=new SimpleDateFormat(KiteDateUtils.DATE_FORMAT);
                        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(signTime))));
                        oppoRes.put("signTime",sd);
                    }
                });
            }
        }
    }
    private void dealGroupOppo(Map<String, Object> oppoData){
        if(KiteMapUtils.isEmpty(oppoData)){
            return;
        }
        Map productData = KiteMapUtils.getMap(oppoData, "productData");
        if(KiteMapUtils.isNotEmpty(productData)){
            List<Map> members = (List<Map>) productData.get("members");
            if(KiteListUtils.isEmpty(members)){
                return;
            }
            for(Map member : members){
                List<Map> serviceAttrs = (List<Map>)member.get("serviceAttrs");
                List<Map> groupAttrs = serviceAttrs.stream().filter(serviceAttr -> KiteStringUtils.isNotEmpty(KiteMapUtils.getString(serviceAttr, "groupId")) && KiteStringUtils.startsWith(KiteMapUtils.getString(KiteMapUtils.getMap(serviceAttr, "attrValues"), "valueName"), "{")).collect(Collectors.toList());
                if(KiteListUtils.isNotEmpty(groupAttrs)){
                    serviceAttrs.removeIf(serviceAttr ->groupAttrs.stream().anyMatch(grpAttr->KiteMapUtils.getString(grpAttr,"attrCode").equals(serviceAttr.get("attrCode"))));
                    groupAttrs.forEach(groupAttr->{
                        String attrValues = KiteMapUtils.getString(KiteMapUtils.getMap(groupAttr,"attrValues"),"valueName");
                        JSONObject jsonObject = JSON.parseObject(attrValues);
                        Map tempMap = new HashMap();
                        tempMap.put("groupId",KiteMapUtils.getString(groupAttr,"groupId"));
                        tempMap.put("groupName",KiteMapUtils.getString(groupAttr,"groupName"));
                        Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
                        List<Object> gropAttrs = entries.stream().map(en -> en.getValue()).collect(Collectors.toList());
                        tempMap.put("gropAttrs",gropAttrs);
                        member.put("groupData",tempMap);
                    });
                }
            }
        }
    }
}
